<template>
  <div>
    <el-card>
      <div slot="header" class="clearfix">
        <span>用户角色授权 - {{ userName }}</span>
      </div>
      
      <div style="margin-bottom: 20px">
        <el-tag>已分配角色</el-tag>
        <el-tag type="info" v-for="role in assignedRoles" :key="role.id" closable @close="removeRole(role.id)">
          {{ role.roleName }}
        </el-tag>
        <el-button type="primary" @click="showSelectRoleDialog" :disabled="allRoles.length === assignedRoleIds.length">
          <i class="el-icon-plus"></i> 分配角色
        </el-button>
      </div>

      <!-- 角色选择对话框 -->
      <el-dialog
        title="选择角色"
        :visible.sync="dialogVisible"
        width="800px"
        :before-close="handleClose"
      >
        <el-transfer
          v-model="selectedRoleIds"
          :data="processedRoles"
          :props="{
            key: 'id',
            label: 'roleName'
          }"
          :titles="['可选角色', '已选角色']"
          @change="handleChange"
          style="display: flex; justify-content: center;"
          :height="300"
          :button-texts="['移除', '添加']"
        ></el-transfer>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="saveAssignments">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'UserAuth',
  data() {
    return {
      userId: '',
      userName: '',
      allRoles: [], // 所有角色
      assignedRoles: [], // 已分配的角色
      assignedRoleIds: [], // 已分配角色的ID数组
      selectedRoleIds: [], // 选中的角色ID数组（用于transfer组件）
      dialogVisible: false,
      loading: false
    }
  },
  computed: {
    // 原始角色数据处理
    processedRoles() {
      return this.allRoles.map(role => ({
        ...role
      }))
    }
  },
  created() {
    // 从路由参数中获取用户ID和用户名
    this.userId = this.$route.params.id
    this.userName = this.$route.query.userName || '未知用户'
    this.loadUserData()
  },
  methods: {
        // 加载用户角色数据
        async loadUserData() {
            try {
                const response = await this.$API.user.getUserRoles(this.userId)
                // 兼容不同的成功状态码
                if (response && (response.code === 200 || response.code === 0 || !response.code)) {
                    const data = response.data || response
                    this.allRoles = data.allRoles || []
                    this.assignedRoles = data.assignedRoles || []
                    
                    // 初始化已分配角色ID数组
                    this.assignedRoleIds = this.assignedRoles.map(role => role.id)
                    
                    // 默认将已分配的角色设置为已选（显示在右侧）
                    this.selectedRoleIds = [...this.assignedRoleIds]
                }
            } catch (error) {
                this.$message.error('获取数据失败，请稍后重试')
                console.error('获取用户角色数据失败:', error)
            }
        },
        
    
    
    // 显示角色选择对话框
    showSelectRoleDialog() {
      // 显示对话框，不需要重置选择，因为loadUserData已经设置了默认选中的角色
      this.dialogVisible = true
    },
    
    // 处理选择变化
    handleChange(values) {
      this.selectedRoleIds = values
    },
    
    // 关闭对话框
    handleClose() {
      this.dialogVisible = false
    },
    
    // 保存角色分配
    async saveAssignments() {
      if (this.selectedRoleIds.length === 0) {
        this.$message.warning('请选择要分配的角色')
        return
      }
      
      try {
        this.loading = true
        const roleIds = this.selectedRoleIds.join(',')
        const response = await this.$API.user.assignRoles(this.userId, roleIds)
        
        // 兼容不同的成功状态码
        if (response && (response.code === 200 || response.code === 0 || !response.code)) {
          this.$message.success(response?.msg || '角色分配成功')
          this.dialogVisible = false
          this.loadUserData() // 重新加载数据
        } else {
          this.$message.error(response?.msg || '角色分配失败')
        }
      } catch (error) {
        this.$message.error('角色分配失败，请稍后重试')
        console.error('分配角色失败:', error)
      } finally {
        this.loading = false
      }
    },
    
    // 移除已分配的角色
    async removeRole(roleId) {
      try {
        // 计算需要保留的角色ID（排除要移除的角色）
        const remainingRoleIds = this.assignedRoleIds.filter(id => id !== roleId).join(',')
        const response = await this.$API.user.assignRoles(this.userId, remainingRoleIds)
        
        if (response && (response.code === 200 || response.code === 0)) {
          this.$message.success('移除角色成功')
          this.loadUserData() // 重新加载数据
        } else {
          this.$message.error(response?.msg || '移除角色失败')
        }
      } catch (error) {
        this.$message.error('移除角色失败，请稍后重试')
        console.error('移除角色失败:', error)
      }
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: center;
}
</style>